package com.bite.redis.Interceptor;


import Constants.JwtConstants;
import Utils.JwtUtil;
import domain.MyThreadLocal;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /*//获取用户ID信息，并将该信息保存到ThreadLocal中
        String userId = request.getHeader("userId");
        //判断是否为空
        if (userId != null){
            MyThreadLocal.set(userId);
            log.info("用户ID为userId:{}",userId);
        }*/
        /*if (request.getRequestURL().toString().contains("semiLogin")){
            return true;
        }*/

        String token = request.getHeader(JwtConstants.TOKEN);
        if (token == null || token.isBlank() || token.isEmpty()){
            log.error("token为空或者不存在");
            return true;
        }
        Claims claims;
        try {
            claims = JwtUtil.parseJWT(token, secret);
        }catch (Exception e){
            log.error("token解析失败");
            return true;
        }
        String userKey = claims.get(JwtConstants.USER_KEY).toString();
        String uId = claims.get(JwtConstants.USER_ID).toString();
        MyThreadLocal.set(uId);
        log.info("用户ID为userId:{}",uId);
        Boolean aBoolean = stringRedisTemplate.hasKey(userKey);
        if (Boolean.FALSE.equals(aBoolean)){
            log.error("令牌已过期");
            return false;
        }
        if (stringRedisTemplate.getExpire(userKey) < JwtConstants.EXPIRATION_REFRESH){
            //刷新时间
            stringRedisTemplate.expire(userKey,JwtConstants.EXPIRATION, TimeUnit.MINUTES);
        }

        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        MyThreadLocal.remove();
    }

}
